package callgraph.process;

import callgraph.domain.JarConfig;
import callgraph.domain.ProfilingFilter;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;

import static callgraph.process.CallGraphProcessor.jarNum;

public class CallGraphPipeline {

    public static void handle(JarConfig jarConfig, Map<String, Set<String>> calleeMethodMapGlobal) throws IOException {
        String outputFilePath = "G:\\workspace\\accurate-testing\\ydxasm\\output\\test.txt";
        try (BufferedWriter resultWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath)));) {
            CallGraphProcessor processor = firstProcessor(jarConfig, resultWriter, calleeMethodMapGlobal);
            jarNum.incrementAndGet();
            while (true) {
                if (!processor.handle()) {
                    break;
                }
                if (processor.next() == null) {
                    break;
                }
                processor = processor.next();
            }
            CallGraphProcessStorage storage = processor.dumpStorage();
            System.out.println(new ObjectMapper().writeValueAsString(storage));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static CallGraphProcessor firstProcessor(JarConfig jarConfig, BufferedWriter resultWriter, Map<String, Set<String>> calleeMethodMapGlobal) throws IOException {
        CallGraphProcessStorage storage = new CallGraphProcessStorage(calleeMethodMapGlobal);
        ProfilingFilter profilingFilter = new ProfilingFilter(jarConfig);
        JarFile jarFile = new JarFile(jarConfig.getJarUrl());
        return new PreHandleJar(storage, profilingFilter, jarConfig, jarFile, resultWriter);
    }
}
